package com.zzh.interview.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.zzh.interview.annotation.HotKeyCache;
import com.zzh.interview.annotation.TestHot;
import com.zzh.interview.common.BaseResponse;
import com.zzh.interview.common.ResultUtils;
import com.zzh.interview.model.dto.TestRequest;
import com.zzh.interview.model.entity.Tag;
import com.zzh.interview.service.TagService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.sql.rowset.spi.SyncResolver;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 张 志 豪
 * @version 1.0
 */
@RestController
@RequestMapping("/tag")
public class TagController {

    @Resource
    private TagService tagService;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    Gson gson = new Gson();

    @GetMapping("/getAllTags")
    public BaseResponse<Set<String>> getAllTags() {
        String cacheKey = "mianshikaola:tagList";
        if (redisTemplate.hasKey(cacheKey)) {
            // 如果缓存中存在结果，直接从缓存中获取
            return ResultUtils.success(gson.fromJson(redisTemplate.opsForValue().get(cacheKey), Set.class));
        } else {
            List<Tag> tagList = tagService.list(new QueryWrapper<Tag>().select("name"));
            Set<String> tagNameSet = tagList.stream().map(tag -> tag.getName()).collect(Collectors.toSet());
            // 将 JSON 数据存入缓存，并设置过期时间（例如 30 分钟）
            String jsonData = gson.toJson(tagNameSet);
            redisTemplate.opsForValue().set(cacheKey, jsonData, 30, TimeUnit.MINUTES);
            return ResultUtils.success(tagNameSet);
        }
    }
}
